/**
 * Copyright (c) 2018-2024, NXOS Development Team
 * SPDX-License-Identifier: Apache-2.0
 * 
 * Contains: pipe test 
 * 
 * Change Logs:
 * Date           Author            Notes
 * 2024-11-09     JasonHu           Init
 */

#include <test/integration.h>
#define NX_LOG_NAME "pipe"
#include <base/log.h>
#include <base/pipe.h>
#include <base/thread.h>
#include <base/debug.h>
#include <base/string.h>

#ifdef CONFIG_NX_TEST_INTEGRATION_PIPE

#define TEST_PIPE_NAME "test_pi0"

NX_PRIVATE void Thread1(void *arg)
{
    NX_Pipe *pi0;
    NX_Size nrecv;
    char buf[256];

    pi0 = NX_PipeConnectByName(TEST_PIPE_NAME);
    NX_ASSERT(pi0);
    NX_PipeIncrease(pi0);

    NX_ASSERT(NX_PipeRecv(pi0, buf, 256, &nrecv) == NX_EOK);
    NX_ASSERT(nrecv == 20);
    NX_PipeDisconnect(pi0);

    NX_PipeDecrease(pi0);

    NX_LOG_D("recv: %s", buf);
}

NX_INTEGRATION_TEST(NX_Pipe)
{
    NX_Thread *t0;
    NX_Size nsend;
    NX_Pipe *pi0 = NX_NULL;

    pi0 = NX_PipeCreate(TEST_PIPE_NAME, 16, NX_PIPE_SEND);
    NX_ASSERT(pi0 != NX_NULL);

    NX_PipeIncrease(pi0);

    NX_PipeConnectByPipe(pi0, NX_PipeIsMaster(pi0));

    t0 = NX_ThreadCreate("t0", Thread1, NX_NULL, NX_THREAD_PRIORITY_NORMAL);
    NX_ASSERT(t0 != NX_NULL);

    NX_ThreadStart(t0);

    NX_ASSERT(NX_PipeSend(pi0, "hellohellohellohello", 20, &nsend) == NX_EOK);
    NX_ASSERT(nsend == 20);

    NX_PipeDisconnect(pi0);

    NX_ThreadWait(t0, NX_NULL);

    NX_PipeDecrease(pi0);

    return NX_EOK;
}

#endif
